import Common from "../common/Common";
import UserInfo from "../UserInfo";
import PlayerData from "../PlayerData";
import UIManager from "./UIManager";
import Define from "../common/Define";

// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html
const {ccclass, property} = cc._decorator;

@ccclass
export default class HttpManager {

    //返回一个静态的函数
    static instance:HttpManager;
    static getInstance():HttpManager{
        if(HttpManager.instance == null){
            HttpManager.instance = new HttpManager();
        }
        return HttpManager.instance;
    }

    httpGets(url,callBack){
        let xhr = cc.loader.getXMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if(xhr.status >= 200 && xhr.status < 300){
                    var respone = xhr.responseText;
                    callBack(respone);
                }
            }
        };
        xhr.open("GET", url, true);
        if (cc.sys.isNative) {
            xhr.setRequestHeader('Access-Control-Allow-Origin','*');
        }
 
        xhr.timeout = 5000;// 5 seconds for timeout
        
        xhr.send();
    }

    httpPost (url,params, callback) {

        //发送合适的请求头信息
        let xhr = cc.loader.getXMLHttpRequest();
        xhr.onreadystatechange = function () {
            // readyState值说明  
            // 0：请求未初始化，还没有调用 open()
            // 1：请求已经建立，但是还没有发送，还没有调用 send()
            // 2：请求已发送，正在处理中（通常现在可以从响应中获取内容头）
            // 3：请求在处理中；通常响应中已有部分数据可用了，没有全部完成
            // 4：响应已完成；您可以获取并使用服务器的响应
            if(xhr.readyState == 4){
                console.log('xhr.readyState='+xhr.readyState+'  xhr.status='+xhr.status);
                if(xhr.status >= 200 && xhr.status < 300){
                    var respone = xhr.responseText;
                    callback(respone);
                }else{
                    callback(-1);
                }
            }
        };
        xhr.open("POST", url, true);
        /*
        当我们创建一个异步对象XMLHttpRequest同时post方式向后台传输数据的时候。
        我们要设置异步对象的xhr.setRequestHeader成员的值为
        XMLHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        */
        //设置头
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
 
        xhr.timeout = 5000;// 5 seconds for timeout
        console.log("send")
        xhr.send(params);
        
    }

    //登录微信
    loginWX(code:string){
        let netData = "code="+code
        console.log("开始执行登陆自己的服务器 netData = "+netData);
        HttpManager.getInstance().httpPost(Define.strIp+Define.strPort+"/users/loginWX",netData,function(res){
            console.log("服务器回调")
            console.log(res);
            let data = JSON.parse(res)
            UserInfo.openid = data.openid
            UserInfo.serverMaxScore = data.score
            console.log("UserInfo.openid" + UserInfo.openid)
            console.log("UserInfo.serverMaxScore" + UserInfo.serverMaxScore)
            console.log("UserInfo.maxScore" + UserInfo.maxScore)
            if(UserInfo.maxScore > UserInfo.serverMaxScore){
                HttpManager.getInstance().submitUserInfo();
            }
            if(!Common.isInMainViewLogin){ //在排行榜点击的登录成功
                HttpManager.getInstance().submitUserInfo();
                UIManager.getInstance().refreshView(Define.viewRanking);
            }
        }.bind(this))
    } 

    //上传服务器的信息
    submitUserInfo(){
        //不用上传分数
        console.log("submitUserInfo 00  UserInfo.openid = " + UserInfo.openid)
        if(UserInfo.openid == ""){
            return;
        }

        console.log("submitUserInfo 00  UserInfo.maxScore = " + UserInfo.maxScore)
        console.log("submitUserInfo 00  UserInfo.serverMaxScore = " + UserInfo.serverMaxScore)
        if(UserInfo.maxScore <= UserInfo.serverMaxScore){
            return
        }

        UserInfo.serverMaxScore = UserInfo.maxScore;
        let netData = "openid="+UserInfo.openid;
        netData = netData + "&avatarUrl="+UserInfo.avatarUrl;
        netData = netData + "&nickName="+UserInfo.nickName;
        netData = netData + "&score="+UserInfo.maxScore;
        console.log("netData = " + netData)
        HttpManager.getInstance().httpPost(Define.strIp+Define.strPort+"/users/submitInfo",netData,function(res){
            console.log("submitUserInfo 数据成功")
 
        }.bind(this))
    }
    //返回排行榜数据
    ranking(callBack:Function){
        HttpManager.getInstance().httpPost(Define.strIp+Define.strPort+"/users/ranking","",function(res){
            console.log("ranking 服务器回调")
            let data = JSON.parse(res)
            console.log("数组的长度 = " + data.length);
            let dataArr:PlayerData[] = [];
            for (var i:number = 0; i < data.length; i++) {
                
                let userData:PlayerData = new PlayerData();
                userData.avatarUrl = data[i].avatarUrl
                userData.score = data[i].score
                userData.nickName = data[i].nickName
                userData.isSelf = data[i].openid == UserInfo.openid
                userData.rank = i + 1;
                dataArr.push(userData)
            }
            callBack(dataArr)
        }.bind(this))
    }

    getGameState(callBack:Function){
        let netData = "gameid="+Define.gameId
        HttpManager.getInstance().httpPost(Define.strIp+Define.strPort+"/users/gameState",netData,function(res){
            let data = JSON.parse(res)
            console.log("ssssssssssssssssss" + data.state)
            if(data.state == "-1"){
                UIManager.getInstance().showView(Define.viewBlack)
            }else{
                callBack();
            }
        }.bind(this))
    }
}
